package com.gopay.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.gopay.scheduler.job.EventsHandlerJob;

/**
 * This class is the abstract base job class to implement.
 * 
 * Its main responsibilities includes: 1. setup SIFT log context (shift this
 * responsibility from child class); 2. exception handling (protect the
 * framework); 3. enable the global context injection.
 * 
 * Concrete child class should inherit this class and implement the
 * doJobInternal() method to do the job task.
 * 
 * @author yangsun
 */
public abstract class GopayBaseJob {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public final void doJob() {


        checkAndSetJobName();
        setupLogMDC();

        try {
            
            if(!(this instanceof EventsHandlerJob)){
                logger.info(this.getClass().getSimpleName()+"------start------");
            }
            //2018/05/29 byp 添加下行代码
            JobProcessorWrapper.getSingle().doJobInternal(this);
            // 2018/05/29 byp 注释掉下行代码 doJobInternal()
            //doJobInternal();
            
             if(!(this instanceof EventsHandlerJob)){
                logger.info(this.getClass().getSimpleName()+"------end------");
            }
            
        } catch (Exception e) {
            logger.error(this.getClass().getSimpleName()+"------error出错啦------", e);
        }
    }

    protected abstract void doJobInternal();
    
   

    public int getSemaphore() {
        return 1;
    }

    private void checkAndSetJobName() {
        String jobPackage = getClass().getPackage().getName();
        String jobName = getClass().getSimpleName();

        if (!jobPackage.equalsIgnoreCase("com.gopay.scheduler.job")) {
            // force console output
            System.err.println("工作任务需要定义在com.gopay.scheduler.job包中");
        }
        if (!jobName.endsWith("Job")) {
            // force console output
            System.err.println("工作任务类类名需要以Job结尾");
        }
    }

    private void setupLogMDC() {
        String jobName = getClass().getSimpleName();

        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

        // 每个job一个日志目录 edit by fanghw 20150515
        MDC.put("jobId", jobName + "/" + jobName + "_" + df.format(now));
    }


    //2018/05/29 byp 添加下行代码
    /**
     * lucky lucky
     */
    private Map<String,Object> luckyParam;

    public void luckyParam(Map<String,Object> luckyParam){
        this.luckyParam = luckyParam;
    }

    public void clearParam(){
        luckyParam = null;
    }
    public Map<String,Object> getParam(){
        return this.luckyParam;
    }
    // 2018/05/29 byp 注释掉下行代码
    
}
